package com.hongyi.app.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hongyi.app.entity.UserNo;
import com.hongyi.app.mapper.UserNoMapper;
import com.hongyi.app.service.UserNoService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author HongYi
 */
@Slf4j
@Data
public class UserNoServiceImpl implements UserNoService {
    private UserNoMapper userNoMapper;

    //测试懒加载
    public UserNoServiceImpl() {
        log.info("UserNoServicelmpl的构造器被执行");
    }

    //测试生命周期
    public void init() {
        log.info("UserNoServicelmpl的init()方法被执行...");
    }

    public void destroy() {
        log.info("UserNoServicelmpl的destroy()方法被执行...");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int generate(Integer num) {

        //总影响条目数
        int result = 0;

        //插入数量num不能小于等于0
        if (num < 0) {
            log.warn("至少生成一条。");
        }

        //按编号降序，查询最后一条编号记录
        UserNo lastUserNo = userNoMapper.selectByStatus(null, "number desc");
        if (lastUserNo == null) {

            log.warn("查询最后一条编号记录失败");
            return 0;
        }

        //获取最后一条UserNo记录的number值
        String number = lastUserNo.getNumber();
        for (int i = 0; i < num; i++) {
            //准备UserNo实例
            UserNo userNo = new UserNo();
            userNo.setStatus(1);

            //准备编号
            String nextNumber = Integer.parseInt(number) + i + 1 + "";
            userNo.setNumber(nextNumber);

            //准备得分
            double score = 30.0;
            //方式二，将nextNumber转换成char[],使用foreach遍历，有一个6，让一个为零的变量++
            nextNumber = nextNumber.replace("6", "");
            score += (7 - nextNumber.length()) * 10;
            userNo.setScore(score);

            //添加编号记录
            int insertResult = userNoMapper.insert(userNo);
            if (insertResult < 0) {
                throw new RuntimeException("添加编号记录操作异常，事务回滚...");
            }

            result += insertResult;
        }
        return result;

    }

    @Override
    public UserNo selectUnusedByUserNo() {


        UserNo userNo = userNoMapper.selectByStatus(1, null);
        UserNo errorUserNo = new UserNo();
        errorUserNo.setId(-1);
        errorUserNo.setInfo("查询失败，编号已全被使用");

        return userNo != null? userNo:errorUserNo;
    }

    @Override
    public PageInfo<UserNo> paging(Integer num, Integer size) {

        //PageHelper的API和全查之间不能加入其他代码
        PageHelper.startPage(num,size);
        List<UserNo> list = userNoMapper.selectlist();
        if(list != null ){
            return  new PageInfo<>(list);
        }

        return new PageInfo<>();
    }


}
